import { asyncRoutes, constantRoutes } from '@/router'

// 判断是否拥有权限
function hasPermission (roles, route) {
  // console.log('roles, route', roles, route)
  if (route.meta && route.meta.roles) {
    // 如果路由需要权限 则判断一下这个页面所需权限是否被用户权限所包含
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    // 如果路由不需要权限 则直接跳转
    return true
  }
}

// 筛选异步路由
export function filterAsyncRoutes (routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }

    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
      // console.log('res.push(tmp)', res)
    }
  })

  return res
}

const permission = {
  state: {
    routes: constantRoutes,
    addRoutes: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    }
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit }, role) {
      // console.log('GenerateRoutes:', role)
      return new Promise(resolve => {
        const roles = role
        // accessedRoutes 访问路由
        let accessedRoutes
        if (roles.includes('admin')) {
          accessedRoutes = asyncRoutes
        } else {
          accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
        }
        // console.log('accessedRoutes:', accessedRoutes)
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    }
  }
}

export default permission
